﻿using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using BlackBeltCoder;
using Microsoft.VisualBasic.Logging;

namespace DownLoadFtpFile
{
    public class Logger
    {
        public static Log Log;

        static Logger()
        {
            Log = new Log(Console.Title);
            Log.DefaultFileLogWriter.AutoFlush = true;
            Log.DefaultFileLogWriter.BaseFileName = Console.Title;
            Log.DefaultFileLogWriter.MaxFileSize = 10 * 1024 * 1024;
            Log.DefaultFileLogWriter.CustomLocation = Environment.CurrentDirectory;
            Log.DefaultFileLogWriter.Append = true;
            Log.DefaultFileLogWriter.IncludeHostName = true;
            Log.WriteEntry("FTPFileDownLoader Start...");
        }
    }

    internal class Program
    {
        static Program()
        {
            Console.Title = "FTPFileDownLoader";
            var w = FindWindow("ConsoleWindowClass", Console.Title);
            if (w != IntPtr.Zero)
                ShowWindow(w, 0);
        }

        [DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)]
        private static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);

        [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        private static void Main(string[] args)
        {
            try
            {
                var localDir = ConfigurationManager.AppSettings["LocalDirectory"];
                if (!Directory.Exists(localDir))
                {
                    Directory.CreateDirectory(localDir);
                }
                else
                {
                    var strDay = ConfigurationManager.AppSettings["Day"];
                    var day = int.Parse(strDay);
                    DeleteFileByTime(localDir, day);
                }
                DownloadLastFile(localDir);
            }
            catch (Exception e)
            {
                Logger.Log.WriteEntry(e.ToString());
            }
            finally
            {
                Logger.Log.WriteEntry("FTPFileDownLoader End...");
            }
        }

        /// <summary>
        ///     删除几天前的文件，0不做删除
        /// </summary>
        /// <param name="day"></param>
        private static void DeleteFileByTime(string localDir, int day)
        {
            if (day == 0)
                return;
            var dateTime = DateTime.Now.AddDays(-day);
            var files = Directory.GetFiles(localDir);
            foreach (var file in files)
                try
                {
                    var fileInfo = new FileInfo(file);
                    if (fileInfo.LastWriteTime < dateTime || fileInfo.LastWriteTime == dateTime)
                        File.Delete(file);
                }
                catch (Exception ex)
                {
                    Logger.Log.WriteEntry(string.Format("删除文件:{0}出错！错误信息:{1}", file, ex.ToString()));
                }
        }


        private static void DownloadLastFile(string localDir)
        {
            var host = ConfigurationManager.AppSettings["Host"];
            var userName = ConfigurationManager.AppSettings["UserName"];
            var passWord = ConfigurationManager.AppSettings["Password"];
            var ftpHelper = new FtpHelper(host, userName, passWord);
            var list = ftpHelper.ListDirectory();
            if (list == null || list.Count < 1)
                return;
            var entries = list.OrderBy(p => p.CreateTime);
            var last = entries.Last();
            ftpHelper.DownloadFiles(localDir, last.Name);
        }

        /// <summary>
        ///     从服务器上获取最新的文件到本地
        /// </summary>
        /// <param name="localDir"></param>
        /// <returns></returns>
        private static string GetLastFile(string localDir)
        {
            var ftpClient = new FtpClient
            {
                Host = ConfigurationManager.AppSettings["Host"],
                Username = ConfigurationManager.AppSettings["UserName"],
                Password = ConfigurationManager.AppSettings["Password"]
            };
            var list = ftpClient.ListDirectory();
            if (list == null || list.Count < 1)
                return string.Empty;
            var entries = list.OrderBy(p => p.CreateTime);
            var last = entries.Last();
            ftpClient.DownloadFiles(localDir, last.Name);
            var file = Path.Combine(localDir, last.Name);
            return file;
        }
    }
}